/*
 * Copyright 2013 Krzysztof Smigielski
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.nilcaream.dirstore.core.common;

import com.nilcaream.dirstore.core.model.TrimmedElement;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.io.IOException;
import java.io.InputStream;

/**
 * TODO
 * <p/>
 * Krzysztof Smigielski 7/7/13 1:14 PM
 */
@Singleton
public class TypeAwareTrimmer {

    @Inject
    private ImageTrimmer imageTrimmer;
    @Inject
    private FileTrimmer fileTrimmer;

    @Inject
    @Named("maxImageSize")
    private int maxImageSize = 100;

    @Inject
    @Named("maxFileSize")
    private int maxFileSize = 1000;

    public TrimmedElement trim(InputStream inputStream, String name) throws IOException {
        TrimmedElement result = new TrimmedElement();
        if (isImage(name)) {
            ImageTrimmer.Result image = imageTrimmer.trim(inputStream, maxImageSize);
            if (image != null) {
                result.setData(image.getData());
                result.setComment(String.format("r:%dx%d", image.getWidth(), image.getHeight()));
            }
        }
        if (result.getData() == null) {
            result.setData(fileTrimmer.trim(inputStream, maxFileSize));
            result.setCompressionNeeded(true);
        }
        return result;
    }

    private boolean isImage(String name) {
        String lower = name.toLowerCase();
        return lower.endsWith(".jpg") || lower.endsWith(".jpeg");
    }
}
